function makeRunData_providerAdoptions(runId)

addpath('../general_funcs');

config = getConfig_providerAdoptions(runId);

if config.modelId == 3
	makeRunData_providerAdoptions_ctsTime(runId);
	return;
end

dataId = config.dataId;

runDataFile           = config.runDataFile;
dynPredInputFile      = config.dynPredInputFile;

%%%%% Get covariates (including FEs)
covariates = config.covariates;

myX_tk_names   = covariates.myX_tk_names;
myX_tk_transfs = covariates.myX_tk_transfs;

myZ_names	= covariates.myZ_names;
myZ_transfs	= covariates.myZ_transfs;

myAnames	= covariates.myAnames;
myAtransfs	= covariates.myAtransfs;

myZ_geo_FE_Names  = covariates.myZ_geo_FE_Names;
time_FE_Names = covariates.time_FE_Names;

%%% Load files
data1 = loadDataFiles(dataId);

NewConsumers        = data1.NewConsumers;        % (T*K1*K2) x 1 (sparse)
NewProviders         = data1.NewProviders;         % T x K
DeletedProviders     = data1.DeletedProviders;     % T x K
laggedConsumersOrig = data1.laggedConsumersOrig; % T x K1
laggedConsumersDest = data1.laggedConsumersDest; % T x K2
laggedProviders      = data1.laggedProviders;      % T x K
population        = data1.population;        % K x 1
surfaces          = data1.surfaces;          % K x 1
incomingCommuters = data1.incomingCommuters; % K x 1
touristBeds       = data1.touristBeds;       % K x 1
periodLabels = data1.periodLabels;
geoLabels0   = data1.geoLabels;
A     = data1.A;
Z     = data1.Z;
X     = data1.X;
Anames     = data1.Anames;
Znames     = data1.Znames;
Xnames     = data1.Xnames;
surfaceName         = data1.surfaceName;
geoAggLevelNames    = data1.geoAggLevelNames;
geoAggLevelLabels   = data1.geoAggLevelLabels;
timeAggLevelNames   = data1.timeAggLevelNames;
timeAggLevelLabels = data1.timeAggLevelLabels;

% Read dimensions
[T,K] = size(NewProviders);
K1 = K;
K2 = K;

%%% Make Y (=NewProviders)
Y = NewProviders;
clear NewProviders;


%%% Make logLambdaOffset and popAtRisk
marketSize = Z(:,find(strcmp(Znames, 'NumHHsWithCar'))); % K x 1
initialSeed = laggedProviders(1,:)'; % K x 1
popAtRisk = marketSize' - laggedProviders; % T x K2
logLambdaOffset = log(popAtRisk); % T x K2


% Reshape Y, installed bases and logLambdaOffset
Y                 = reshape(Y, [T*K 1]); % (T*K) x 1
laggedProviders      = reshape(laggedProviders, [T*K2 1]); % (T*K2 x 1)
laggedConsumersOrig = reshape(laggedConsumersOrig, [T*K1 1]); % (T*K1 x 1)
laggedConsumersDest = reshape(laggedConsumersDest, [T*K2 1]); % (T*K2 x 1)
logLambdaOffset   = reshape(logLambdaOffset, [T*K2, 1]); % (T*K) x 1


% Get myX_tk and myX_tk_names
[Xflag, X_idces] = ismember(myX_tk_names, Xnames);
if any(~Xflag); error('Could not find all Xnames.'); end;
if any(~strcmp(Xnames(X_idces), myX_tk_names)); error('Mistmatch'); end;
myX_tk         = X(:,:, X_idces);				% T x K x NumX
myX_tk         = reshape(myX_tk, T*K, size(myX_tk,3));	% (T*K) x NumX
[myX_tk, myX_tk_names] = transformMatrix(myX_tk, myX_tk_transfs, myX_tk_names, reshape(repmat(surfaces', T, 1), T*K, 1),surfaceName);
	% (T*K) x NumX and cell(1,NumX) of strings

% Get myZ and myZ_names
[Zflag, Z_idces] = ismember(myZ_names, Znames);
if any(~Zflag); error('Could not find all Znames.'); end;
if any(~strcmp(Znames(Z_idces), myZ_names)); error('Mistmatch'); end;
myZ         = Z(:, Z_idces);				% K x NumZ
[myZ, myZ_names] = transformMatrix(myZ, myZ_transfs, myZ_names, surfaces, surfaceName);
	% K x NumZ and cell(1,NumZ) of strings

% Get myA and myAnames
[Aflag, A_idces] = ismember(myAnames, Anames);
if any(~Aflag); error('Could not find all Anames.'); end;
if any(~strcmp(Anames(A_idces), myAnames)); error('Mistmatch'); end;
myA         = A(:, A_idces);				% T x NumA
	% T x NumA and cell(1,NumA) of strings

% Add intercept to myA
myA = [ones(T,1) myA];
myAnames = [{'Intercept'} myAnames];
myAtransfs = [-1 myAtransfs];


%% Make time_FEs (I'm not using timeAggLevelNames and timeAggLevelLabels here but I could...)
[flag, idxes] = ismember(time_FE_Names, Anames);
if any(~flag); error('Could not find all time FE names.'); end;
time_FEs = A(:,idxes);
Num_time_FE_sets = length(time_FE_Names);
Num_time_FE_vals = zeros(1,Num_time_FE_sets);
time_FE_labels = cell(1,Num_time_FE_sets);
for aa = 1:Num_time_FE_sets
	time_FEs_aa = time_FEs(:,aa);
	time_FE_Name_aa = time_FE_Names{aa};
	
	unq_time_FEs_aa = sort(unique(time_FEs_aa));
	time_FE_labels_aa = strcat(time_FE_Name_aa, sprintfc('_is_%d', unq_time_FEs_aa));
	[flag,newTime_FEs_aa] = ismember(time_FEs_aa, unq_time_FEs_aa);
	
	time_FEs(:,aa) = newTime_FEs_aa;
	Num_time_FE_vals(aa) = length(unq_time_FEs_aa);
	time_FE_labels{aa} = time_FE_labels_aa;
end

%% Make  myZ_geo_FEs + get myZ_geo_FE_labels +  myZ_Num_geo_FE_vals
[flag, idxes] = ismember(myZ_geo_FE_Names, Znames);
if any(~flag); error('Could not find all geo FE names.'); end;
myZ_geo_FEs = Z(:,idxes);
Num_geo_FE_sets = length(myZ_geo_FE_Names);
myZ_Num_geo_FE_vals = zeros(1,Num_geo_FE_sets);
myZ_geo_FE_labels = cell(1,Num_geo_FE_sets);
for aa = 1:Num_geo_FE_sets
	geo_FE_Name_aa = myZ_geo_FE_Names{aa};
	[flag,geoidx] = ismember(geo_FE_Name_aa, geoAggLevelNames);
	if ~flag; error('Could not find geo_FE_name among geoAggLevelNames'); end;
	geo_FE_labels_aa = geoAggLevelLabels{geoidx};
	myZ_Num_geo_FE_vals(aa) = length(geo_FE_labels_aa);
	myZ_geo_FE_labels{aa} = geo_FE_labels_aa;
end



%%% Add treatment for initial installed base %%%
if config.initialBaseTreatment
	[myZ, myZ_names] = addInitialBaseCovariate(initialSeed, myZ, myZ_names, 'Providers');
end


%%%% Make Xdynamic_staticInputs and Xparts_dynamic (Xparts that depend on installed base)
Xparts_static{1}.X      = myX_tk;             % (T*K) x NumXstatic
Xparts_static{1}.Xnames = myX_tk_names;       % cell(1,NumXstatic) of strings
Xparts_static{1}.X_FEs        = zeros(T*K,0); % (T*K) x NumX_FEs
Xparts_static{1}.X_FE_labels  = {};           % cell(1, NumX_FEs)
Xparts_static{1}.NumX_FE_vals = zeros(1,0);   % 1 x NumX_FEs

Xdynamic_staticInputs.Xparts_static = Xparts_static;
if config.laggedBaseTransf.code == 1 || config.laggedBaseTransf.code == 3
	Xdynamic_staticInputs.extraArgs     = {};
end
if config.laggedBaseTransf.code == 2 || config.laggedBaseTransf.code == 4  || config.laggedBaseTransf.code == 5
	if strcmp(config.laggedBaseTransf.denom, 'Area')
		surface_rep = reshape(repmat(surfaces', [T, 1]), [T*K 1]); % (T*K) x 1
		Xdynamic_staticInputs.extraArgs = {log(surface_rep)};
	end
end

installedBases.laggedProviders      = laggedProviders;
installedBases.laggedConsumersOrig = laggedConsumersOrig;
installedBases.laggedConsumersDest = laggedConsumersDest;
Xparts_dynamic = make_Xdynamic_providerAdoptions(config, Xdynamic_staticInputs, installedBases, true);

%%%%% Make Xparts and dims %%%%%
dimType = 2;
Xparts = {};
dims1 = {};
Xpart_2_NumX = [];
Xpart_2_NumX_FEs = [];
Xpart_2_Num_FE_vals = {};
NumFEvals2Keep = {};

pidx = 0;

%%% T-K part:
pidx = pidx+1;
obj = Xparts_dynamic{1};
Xparts{pidx}              = obj;
dims1{pidx}               = T*K;
Xpart_2_NumX(pidx)        = size(obj.X,2);
Xpart_2_NumX_FEs(pidx)    = size(obj.X_FEs,2);
Xpart_2_Num_FE_vals{pidx} = obj.NumX_FE_vals;
NumFEvals2Keep{pidx}      = sum(obj.NumX_FE_vals) - length(obj.NumX_FE_vals);

clear X obj;

%%% T part:
X      = myA;      % T x NumX
Xnames = myAnames; % 1 x NumX
X_FEs        = time_FEs;         % T x NumX_FEs
X_FE_labels  = time_FE_labels;   % cell(1, NumX_FEs)
NumX_FE_vals = Num_time_FE_vals; % 1 x NumX_FEs

pidx = pidx+1;
obj.X                     = X;
obj.Xnames                = Xnames;
obj.X_FEs                 = X_FEs;
obj.X_FE_labels           = X_FE_labels;
obj.NumX_FE_vals          = NumX_FE_vals;
Xparts{pidx}              = obj;
dims1{pidx}               = T;
Xpart_2_NumX(pidx)        = size(X,2);
Xpart_2_NumX_FEs(pidx)    = size(X_FEs,2);
Xpart_2_Num_FE_vals{pidx} = NumX_FE_vals;
NumFEvals2Keep{pidx}      = sum(NumX_FE_vals) - length(NumX_FE_vals);

clear X X_FEs NumX_FE_vals obj;

%%% K part:
X      = myZ;        % K x NumX
Xnames = myZ_names;  % 1 x NumX
X_FEs        = myZ_geo_FEs;  % K x NumX_FEs
X_FE_labels  = myZ_geo_FE_labels;   % cell(1, NumX_FEs)
NumX_FE_vals = myZ_Num_geo_FE_vals; % 1 x NumX_FEs

pidx = pidx+1;
obj.X                     = X;
obj.Xnames                = Xnames;
obj.X_FEs                 = X_FEs;
obj.X_FE_labels           = X_FE_labels;
obj.NumX_FE_vals          = NumX_FE_vals;
Xparts{pidx}              = obj;
dims1{pidx}               = K;
Xpart_2_NumX(pidx)        = size(X,2);
Xpart_2_NumX_FEs(pidx)    = size(X_FEs,2);
Xpart_2_Num_FE_vals{pidx} = NumX_FE_vals;
NumFEvals2Keep{pidx}      = sum(NumX_FE_vals) - length(NumX_FE_vals);

clear X X_FEs NumX_FE_vals obj;


%%%%% Make data object
% Calculate NumParams
NumParts = pidx;
NumParams = 0;
for ii = 1:NumParts
	NumParams = NumParams + size(Xparts{ii}.X,2);
	for ff = 1:size(Xparts{ii}.X_FEs,2)
		NumX_FE_vals_if = Xparts{ii}.NumX_FE_vals(ff);
		NumParams = NumParams + NumX_FE_vals_if - 1;
	end
end

% Make dims
dims.dimType  = dimType;
dims.NumParts = NumParts;
dims.NumObs = size(Y,1);
dims.NumParams      = NumParams;
dims.dims1               = dims1;
dims.Xpart_2_NumX        = Xpart_2_NumX;
dims.Xpart_2_NumX_FEs    = Xpart_2_NumX_FEs;
dims.Xpart_2_Num_FE_vals = Xpart_2_Num_FE_vals;
dims.NumFEvals2Keep      = NumFEvals2Keep;

% Make LL_offset
myidxes = find(Y>0);
LL_offset = -sum(gammaln(1+Y(myidxes)));
clear myidxes;

% Make data
clear data; % (Clear previous data object)
data.Y               = Y;                   % (T*K) x 1
data.logLambdaOffset = logLambdaOffset;     % (T*K) x 1
data.LL_offset       = LL_offset;           % scalar
data.Xparts          = Xparts;              % cell(3,1)
data.dims            = dims;                % cell(3,1)
data.periodLabels    = periodLabels;        % cell(T,1)
data.geoLabels       = geoLabels0;          % cell(K,1)
data.surfaces        = surfaces;            % K x 1
data.population      = population;          % K x 1
data.incomingCommuters = incomingCommuters; % K x 1
data.touristBeds       = touristBeds;       % K x 1

% Save to output file
save(runDataFile, 'data', '-v7.3');

% Save things that are useful for dynamic prediction and counterfactuals
base.Y             = data.Y; % (sparse) T x K
base.Xdynamic_staticInputs = Xdynamic_staticInputs; % cell(NumParts,1)
base.laggedConsumersOrig = reshape(laggedConsumersOrig, [T K]);  % T x K
base.laggedConsumersDest = reshape(laggedConsumersDest, [T K]);  % T x K
base.laggedProviders      = reshape(laggedProviders,  [T K]); % T x K
base.popAtRisk     = popAtRisk; % T x K
save(dynPredInputFile, 'base', '-v7.3');

clear;
end